<template>
	<view class="main">
		<view class="title">
			<h2>欢迎登陆图书商城</h2>
		</view>
		<u--form labelPosition="left" class="form" :model="userInfo" :rules="rules" ref="form1">
			<u-form-item label="邮箱" prop="email" borderBottom ref="item1">
				<u--input v-model="userInfo.email" border="none"></u--input>
			</u-form-item>
			<u-form-item label="密码" prop="password" borderBottom ref="item2">
				<u--input v-model="userInfo.password"  type="password" border="none"></u--input>
			</u-form-item>
			<u-button type="primary" text="确定" :disabled="style===true" @click="login"></u-button>
			<view class="footer">
				<navigator url="/register" class="left">找回密码</navigator>
				<!-- <navigator url="/register"  class="right"><button type="default">注册</button></navigator> -->
				<view @click="openView" class="right">注册</view>
			</view>
		</u--form>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: {
					email: 'super@a.com',
					password: '123123',
				},
				rules: {
					// 字段名称
					email: [{
						required: true,
						message: '请输入邮箱',
						trigger: ['change', 'blur'],
						type: 'email'
					}],
					password: [{
						required: true,
						min: 6,
						max: 21,
						message: '长度在2-21个字符之间'
					}]
				},
				//样式
				style: false
			}
		},
		methods: {
			//登录
			login() {
				this.$refs.form1.validate().then( async res => {
					if (res) {
						this.style = false
						let result = await this.$u.api.authLogin(this.userInfo)
						//缓存token
						this.$u.vuex('vuex_token',result.access_token)
						this.$u.toast('登陆成功')
						//请求用户信息
						let resultInfo = await this.$u.api.userInfo()
						this.$u.vuex('vuex_user',resultInfo)
						
						//登录之后跳转到来源页
						let backUrl = uni.getStorageSync('back_url') || 'pages/index/index'
						this.$u.route({
							type:'reLaunch',
							url:uni.getStorageSync('back_url') || 'pages/index/index',
						})
					}
				}).catch(errors => {
					uni.$u.toast(errors)
				})
			},
			openView(){
				this.$u.route({
					type:'reLaunch',
					url:'/pages/auth/register'
				})
			}
		},
	}
</script>

<style>
	.title {
		margin-top: 60rpx;
		text-align: center;
	}

	.form {
		margin: 60rpx;
	}

	.footer {
		margin-top: 20rpx;
	}

	.right {
		float: right;
	}

	.left {
		display: block;
		float: left;
	}
</style>
